package com.hemerasolutions.v2trainer.converter;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;


import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import com.google.api.client.util.DateTime;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("gDateTimeConverter")
@FacesConverter("gDateTimeConverter")
@Scope("request")
public class GDateTimeConverter implements Converter, Serializable {

	private static final long serialVersionUID = 1L;
	

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		GregorianCalendar gc = new GregorianCalendar();
		SimpleDateFormat sdf = new SimpleDateFormat((String) component.getAttributes().get("pattern"));
		Date date;
		try {
			date = sdf.parse(value);
			gc.setTime(date);
			
			return new DateTime(gc.getTimeInMillis());

		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
		
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object object) {

		if(object != null){
			GregorianCalendar gc = new GregorianCalendar();
			
			gc.setTimeInMillis(((com.google.api.client.util.DateTime)object).getValue());
			SimpleDateFormat sdf = new SimpleDateFormat((String) component.getAttributes().get("pattern"));
			return sdf.format(gc.getTime());
		}else{
			return null;
		}
		
	}
	

}

